package cn.edu.ctbu.tydemo1.service.impl;


import cn.edu.ctbu.tydemo1.domain.Student;
import cn.edu.ctbu.tydemo1.exception.REnum;
import cn.edu.ctbu.tydemo1.exception.RException;
import cn.edu.ctbu.tydemo1.repository.StudentRepository;
import cn.edu.ctbu.tydemo1.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentimplService implements StudentService {

    @Autowired
    private StudentRepository studentRepository;


    public List<Student> findAll(){
        return studentRepository.findAll();
    }

    /***
     * 按id进行查询
     * @param id 主键，整数型
     * @return
     */
    public Student findById(Integer id){
        return studentRepository.findById(id).orElse(null);
    }

    /***
     * 按name进行查询，like
     * @param name 姓名，字符型
     * @return
     */
    public List<Student> findByName(String name){
        return studentRepository.findByNameLike(name);
    }

//    /***
//     * 按名字和密码查询
//     * @param name 姓名,字符型
//     * @param password 密码，字符型
//     * @return
//     */
//    public List<Student> findByNameAndPassword(String name,String password){
//        return studentRepository.findByNameAndPassword(name,password);
//    }


    /**
     * 只支持分页的查询
     * @param pageable
     * @return
     */
    public Page<Student> findAll(Pageable pageable){

        return studentRepository.findAll(pageable);
    }

    /**
     * 分页，带过滤的查询
     * @param student
     * @param pageable
     * @return
     */
    public Page<Student> findAll(Example<Student> student,Pageable pageable){
        return studentRepository.findAll(student,pageable);
    }
    public Student insert(Student student){
        studentRepository.save(student);
        return student;
    }

    public Student update(Student student){
        studentRepository.save(student);
        return student;
    }


    public void delete(Student student){

        studentRepository.delete(student);
    }

    public void delete(Integer id){

        Student student=new Student();
        student.setId(id);

        studentRepository.delete(student);
    }
    public Student findByNameAndPassword(String name, String password) {
        List<Student> byNameAndPassword = studentRepository.findByNameAndPassword(name, password);
        if (byNameAndPassword.size() > 0) {
            return byNameAndPassword.get(0);
        } else {
            throw new RException(REnum.LOGIN_ERR);

        }

    }
}


